package net.vinote.smart.platform.service.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;

import javax.servlet.http.HttpSession;

import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.log.RunLogger;

public class OnlineUserPool {
	private static OnlineUserPool pool;
	private static Object lock = new Object();
	private Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

	private OnlineUserPool() {
		initSessionClearTask();
	}

	public static OnlineUserPool getInstance() {
		if (pool == null) {
			synchronized (lock) {
				if (pool == null) {
					pool = new OnlineUserPool();
				}
			}
		}
		return pool;
	}

	/**
	 * 记录登录用户的sessionID
	 * 
	 * @param userID
	 * @param sessionID
	 */
	public void setUserSession(String userID, HttpSession session) {
		HttpSession oldSession = sessionMap.get(userID);
		if (oldSession != null) {
			try {
				oldSession.invalidate();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		sessionMap.put(userID, session);
	}

	private void initSessionClearTask() {
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				long curTime = System.currentTimeMillis();
				for (Entry<String, HttpSession> entry : sessionMap.entrySet()) {
					HttpSession session = entry.getValue();
					if (curTime - session.getLastAccessedTime() > session
							.getMaxInactiveInterval() * 1000) {
						sessionMap.remove(entry.getKey());
						RunLogger.getLogger().log(Level.FINER,
								"Clear user " + entry.getKey() + "'s session!");
					}
				}
			}
		};
		new Timer().schedule(task, PlatformConst.TimeConstant.ONE_MINUTE,
				PlatformConst.TimeConstant.ONE_MINUTE);
	}
}
